<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="transferDate">
        <el-date-picker
            v-model="queryParams.transferDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
            clearable
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="操作" prop="operation">
        <el-select v-model="queryParams.operation" placeholder="请选择操作" clearable style="width: 240px">
          <el-option
              v-for="dict in fund_transfer_operation"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证券账号" prop="accountNos">
        <el-select
            v-model="queryParams.accountNos"
            placeholder="请选择证券账号"
            clearable
            multiple
            style="width: 240px"
        >
          <el-option
              v-for="item in accountOptions"
              :key="item.accountNo"
              :label="item.accountName"
              :value="item.accountNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['stock:transfer:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['stock:transfer:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['stock:transfer:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="transferList"
              @selection-change="handleSelectionChange"
              show-summary
              :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="日期" align="center" prop="transferDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.transferDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="transferTime"/>
      <el-table-column label="金额" align="center" prop="amount">
        <template #default="scope">
          {{ formatCurrency(scope.row.amount) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="operation">
        <template #default="scope">
          <dict-tag :options="fund_transfer_operation" :value="scope.row.operation"/>
        </template>
      </el-table-column>
      <el-table-column label="证券账户" align="center" prop="accountNo">
        <template #default="scope">
          {{ getAccountName(scope.row.accountNo) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['stock:transfer:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['stock:transfer:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200,500]"
        @pagination="getList"
    />

    <!-- 添加或修改银证转账对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="transferRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="证券账户" prop="accountNo">
          <el-select v-model="form.accountNo" placeholder="请选择证券账户">
            <el-option
                v-for="item in accountOptions"
                :key="item.accountNo"
                :label="item.accountName"
                :value="item.accountNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="日期" prop="transferDate">
          <el-date-picker
              style="width: 100%"
              v-model="form.transferDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="时间" prop="transferTime">
          <el-input v-model="form.transferTime" placeholder="请输入时间,如：15:30:45"/>
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="操作" prop="operation">
          <el-radio-group v-model="form.operation">
            <el-radio
                v-for="dict in fund_transfer_operation"
                :key="dict.value"
                :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Transfer">
import {addTransfer, delTransfer, getTransfer, listTransfer, updateTransfer} from "@/api/stock/transfer";
import {listAccount} from "@/api/stock/account";
import {formatCurrency} from "@/utils/format.js";

const {proxy} = getCurrentInstance();
const {fund_transfer_operation} = proxy.useDict('fund_transfer_operation');

const transferList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const accountOptions = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    transferDate: null,
    operation: null,
    accountNos: [],
  },
  rules: {
    transferDate: [
      {required: true, message: "日期不能为空", trigger: "blur"}
    ],
    amount: [
      {required: true, message: "金额不能为空", trigger: "blur"}
    ],
    operation: [
      {required: true, message: "操作不能为空", trigger: "change"}
    ],
    accountNo: [
      {required: true, message: "账户不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询银证转账列表 */
function getList() {
  loading.value = true;
  // 将数组转为字符串
  let accountNosString = '';
  if (Array.isArray(queryParams.value.accountNos) && queryParams.value.accountNos.length > 0) {
    accountNosString = queryParams.value.accountNos.join(',');
  } else if (typeof queryParams.value.accountNos === 'string' && queryParams.value.accountNos) {
    accountNosString = queryParams.value.accountNos;
  }
  const queryParamCopy = {...queryParams.value, accountNos: accountNosString};
  listTransfer(queryParamCopy).then(response => {
    transferList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

const getSummaries = (param) => {
  const {columns, data} = param
  const sums = []

  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = '统计'
    }
    if (column.property === 'amount') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
  })

  return sums
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    transferDate: null,
    transferTime: null,
    amount: null,
    operation: '1',
    accountNo: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("transferRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加银证转账";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getTransfer(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改银证转账";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["transferRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTransfer(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTransfer(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除银证转账编号为"' + _ids + '"的数据项？').then(function () {
    return delTransfer(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 是否渲染字段 */
function renderField(insert, edit) {
  return form.value.id == null ? insert : edit;
}

/** 根据账户号码获取账户名称 */
function getAccountName(accountNo) {
  if (!accountNo) return '';
  const account = accountOptions.value.find(item => item.accountNo === accountNo);
  return account ? account.accountName : accountNo;
}

/** 查询账户列表 */
function getAccountList() {
  listAccount({}).then(response => {
    accountOptions.value = response.rows;
  });
}

Promise.all([getList(), getAccountList()]);
</script>